package com.ma.auth.controller;

import com.ma.auth.service.SysMenuService;
import com.ma.auth.service.SysUserService;
import com.ma.common.config.exception.MaException;
import com.ma.common.jwt.JwtHelper;
import com.ma.common.result.Result;
import com.ma.common.utils.MD5;
import com.ma.model.system.SysUser;
import com.ma.vo.system.LoginVo;
import com.ma.vo.system.RouterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/system/index")
@Api(tags = "后台登录管理")
public class IndexController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysMenuService menuService;
    //login
    @ApiOperation("用户登录并返回token")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
        SysUser user = userService.getByUsername(loginVo.getUsername());
        if(user == null){
            throw new MaException(201,"用户不存在");
        }
        //判断密码
        String passwordDB = user.getPassword();
        String password = MD5.encrypt(loginVo.getPassword());
        if(!passwordDB.equals(password)){
            throw new MaException(201,"密码错误");
        }
        //判断用户是否被禁用
        if (user.getStatus() == 0){
            throw new MaException(201,"此用户已经被禁用");
        }
        //使用jwt工具生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getUsername());
        //返回信息
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }

    //info
    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public Result info(HttpServletRequest request){
        //1.从请求头中获取用户信息(token字符串)
        String token = request.getHeader("token");
        // 2.从token字符串中获取用户id或用户名称
        Long userId = JwtHelper.getUserId(token);
        //3.根据用户id查询用户信息
        SysUser sysUser = userService.getById(userId);
        //4.根据用户id获取用户可操作菜单，动态进行显示
        List<RouterVo> routerList = menuService.findUserMenuByUserId(userId);
        //5.根据用户id获取用户可操作按钮列表
        List<String> permsList = menuService.findUserPermsByUserId(userId);
        //返回用户操作菜单
        Map<String,Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",sysUser.getName());
        map.put("routers",routerList);
        //返回用户操作按钮
        map.put("buttons",permsList);
        return Result.ok(map);

    }
    //退出
    @ApiOperation("用户退出")
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }
}
